package com.yuyou.tas.lesson.service.impl;


import com.yuyou.tas.lesson.mapper.BaseChapterMapper;
import com.yuyou.tas.lesson.service.IBaseChapterService;
import com.yuyou.tas.lesson.service.ILessonChapterService;
import com.yuyou.tas.lesson.service.comm.OrganLimitService;
import com.yuyou.tas.lesson.vo.req.ReqAddBaseChapter;
import com.yuyou.tas.lesson.vo.req.ReqUpdateBaseChapter;
import com.yuyou.tas.service.api.admin.service.CommJobAPI;
import com.yuyou.tas.service.api.lesson.dto.DtoBaseChapter;
import com.yuyou.tas.service.api.lesson.entity.BaseChapter;
import com.yuyou.tas.service.api.lesson.entity.LessonResource;
import com.yuyou.tas.util.bean.LoginRedisObj;
import com.yuyou.tas.util.bean.Pagination;
import com.yuyou.tas.util.bean.ResBoolSimpleInfo;
import com.yuyou.tas.util.enums.CommEnums;
import com.yuyou.tas.util.enums.OrganLimitEnums;
import com.yuyou.tas.util.enums.admin.CommJobEnums;
import com.yuyou.tas.util.enums.lesson.LessonChapterEnums;
import com.yuyou.tas.util.exception.BusinessException;
import com.yuyou.tas.util.tool.DefindBeanUtils;
import com.yuyou.tas.util.tool.Sequence;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class BaseChapterServiceImpl implements IBaseChapterService {

    @Autowired
    private BaseChapterMapper mapper;

    @Autowired
    private OrganLimitService organLimitService;

    @Autowired
    private LessonResourceService lessonResourceService;

	@Autowired
    private CommJobAPI commJobAPI;

	@Autowired
	private ILessonChapterService lessonChapterService;
	
    @Override
    @Transactional(rollbackFor=Exception.class,timeout=60)
    public BaseChapter selectByPrimaryKey(Long id){
    	return mapper.selectByPrimaryKey(id);
    }
    
	@Override
	public List<BaseChapter> selectByPrimaryKeys(List<Long> ids) {
		return mapper.selectByPrimaryKeys(ids);
	}
    
    @Override
    @Transactional(rollbackFor=Exception.class,timeout=60)
    public ResBoolSimpleInfo addChapter(ReqAddBaseChapter chapter,Long pId, Long lectureId, Integer isStan, LoginRedisObj user,Long organId) {
        ResBoolSimpleInfo info = new ResBoolSimpleInfo(true,"插入成功");
        BaseChapter bc = new BaseChapter();
        DefindBeanUtils.copyProperties(chapter , bc);
        if(bc.getChapterType() == null){
            bc.setChapterType(LessonChapterEnums.type.upload.getValue());//默认上传讲义
        }
        bc.setId(Sequence.getSequence().nextId());
        bc.setAuthOrganizationId(organId);
        bc.setCreateTime(new Date());
        bc.setCreateUser(user.getUserId());
        bc.setLectureId(lectureId);
        bc.setIsStan(isStan);
        bc.setpId(pId);
        mapper.insert(bc);

        if(bc.getCourseUrl() != null){
            LessonResource lr = lessonResourceService.selectByResourceId(bc.getCourseUrl());
            if(lr != null){//已存在临时数据，改为正式数据
                lr.setIsTemp(0);
                lr.setType(CommEnums.resourceType.COURSE.getValue());
                lessonResourceService.updateByPrimaryKeySelective(lr);
            }else{
                lessonResourceService.addResource(CommEnums.resourceType.COURSE.getValue(),bc.getCourseUrl(), user.getOrganizationId(),null, user.getUserId());
            }
        }
        if(bc.getLectureUrl() != null){
            LessonResource lr = lessonResourceService.selectByResourceId(bc.getLectureUrl());
            if(lr != null){//已存在临时数据，改为正式数据
                lr.setIsTemp(0);
                lr.setType(CommEnums.resourceType.LECTURE.getValue());
                lessonResourceService.updateByPrimaryKeySelective(lr);
            }else{
                lessonResourceService.addResource(CommEnums.resourceType.LECTURE.getValue(),bc.getLectureUrl(), user.getOrganizationId(),null, user.getUserId());
            }
        }



        return info;
    }

    @Override
    @Transactional(rollbackFor=Exception.class,timeout=60)
    public ResBoolSimpleInfo updateChapter(ReqUpdateBaseChapter chapter,Long pId, Long lectureId, Integer isStan, LoginRedisObj user) throws Exception{
        if(!user.getIsSystem()){
            organLimitService.checkOrganByOrganId(user.getOrganizationId(), chapter.getId(), OrganLimitEnums.type.base_chapter);
        }

        ResBoolSimpleInfo info = new ResBoolSimpleInfo(true,"修改成功");
        BaseChapter bc = mapper.selectByPrimaryKey(chapter.getId());

        if(bc != null){
            if(chapter.getDataSubject() != null  && !bc.getDataSubject().equals(chapter.getDataSubject())){//讲次科目发生更改
                List<String> usedList = lessonChapterService.findBaseChaInLesson(bc.getId());
                if(!CollectionUtils.isEmpty(usedList)){//该素材已经被引用
                    if(usedList.size() > 3){
                        List<String> list = usedList.stream().limit(3).collect(Collectors.toList());
                        throw new BusinessException("该讲次已被课程：[ " + String.join(",",list) + "...等" +" ]使用，请先解除关系后再更改科目");
                    }else{
                        throw new BusinessException("该讲次已被课程：[ " + String.join(",",usedList) + " ]使用，请先解除关系后再更改科目");
                    }
                }
            }
        }

        String courseUrl = bc.getCourseUrl();
        String lectureUrl = bc.getLectureUrl();

        DefindBeanUtils.copyProperties(chapter , bc);
        bc.setId(chapter.getId());
        bc.setpId(pId);
        bc.setLectureId(lectureId);
        bc.setIsStan(isStan);
        mapper.updateByPrimaryKeySelective(bc);

        if(bc.getCourseUrl() != null){//课件
            if(courseUrl != null){
                if(!courseUrl.equals(bc.getCourseUrl())){//课件更新
                	//删除旧文件
                	commJobAPI.addResourceJob(courseUrl, CommJobEnums.type.resource.getValue(), CommJobEnums.tag.resource.getValue());

                    LessonResource lr = lessonResourceService.selectByResourceId(bc.getCourseUrl());
                    if(lr != null){//已存在临时数据，改为正式数据
                        lr.setIsTemp(0);
                        lr.setType(CommEnums.resourceType.COURSE.getValue());
                        lessonResourceService.updateByPrimaryKeySelective(lr);
                    }else{
                        lessonResourceService.addResource(CommEnums.resourceType.COURSE.getValue(),bc.getCourseUrl(), user.getOrganizationId(),null, user.getUserId());
                    }
                }
            }else{
                lessonResourceService.addResource(CommEnums.resourceType.COURSE.getValue(),bc.getCourseUrl(), user.getOrganizationId(),null, user.getUserId());
            }

        }else if(courseUrl != null){//课件删除
        	commJobAPI.addResourceJob(courseUrl, CommJobEnums.type.resource.getValue(), CommJobEnums.tag.resource.getValue());
        }

        if(bc.getLectureUrl() != null){//讲义
            if(lectureUrl != null){
                if(!lectureUrl.equals(bc.getLectureUrl())){//讲义更新
                    //删除旧文件
                    commJobAPI.addResourceJob(lectureUrl, CommJobEnums.type.resource.getValue(), CommJobEnums.tag.resource.getValue());

                    LessonResource lr = lessonResourceService.selectByResourceId(bc.getLectureUrl());
                    if(lr != null){//已存在临时数据，改为正式数据
                        lr.setIsTemp(0);
                        lr.setType(CommEnums.resourceType.LECTURE.getValue());
                        lessonResourceService.updateByPrimaryKeySelective(lr);
                    }else{
                        lessonResourceService.addResource(CommEnums.resourceType.LECTURE.getValue(),bc.getLectureUrl(), user.getOrganizationId(),null, user.getUserId());
                    }
                }
            }else{
                lessonResourceService.addResource(CommEnums.resourceType.LECTURE.getValue(),bc.getLectureUrl(), user.getOrganizationId(),null, user.getUserId());
            }

        }else if(lectureUrl != null){//讲义删除
        	//删除旧文件
        	commJobAPI.addResourceJob(courseUrl, CommJobEnums.type.resource.getValue(), CommJobEnums.tag.resource.getValue());
        }

        return info;
    }

    @Override
    @Transactional(rollbackFor=Exception.class,timeout=60)
    public ResBoolSimpleInfo delChapter(Long id){
        Integer usedCount = lessonChapterService.findCountByBaseCha(id);
        if(usedCount != null && usedCount > 0){//该讲次已经被引用了
            List<String> lastUsedName = lessonChapterService.findBaseChaInLesson(id);
            throw new BusinessException("该讲次已经被[" + lastUsedName.get(0) + "]等,"+usedCount + "个课程所引用,请先解除关系,再删除");
        }
        BaseChapter bc = mapper.selectByPrimaryKey(id);
        if(bc != null){
            if(bc.getLectureUrl() != null){
            	commJobAPI.addResourceJob(bc.getLectureUrl(), CommJobEnums.type.resource.getValue(), CommJobEnums.tag.resource.getValue());
            }
            if(bc.getCourseUrl() != null){
                commJobAPI.addResourceJob(bc.getCourseUrl(), CommJobEnums.type.resource.getValue(), CommJobEnums.tag.resource.getValue());
            }
        }
        ResBoolSimpleInfo info = new ResBoolSimpleInfo(true,"删除成功");
        mapper.deleteByPrimaryKey(id);
        return info;
    }

    @Override
    @Transactional(rollbackFor=Exception.class,timeout=60)
    public ResBoolSimpleInfo<BaseChapter> getChapterByID(Long id) {
        BaseChapter bc = mapper.selectByPrimaryKey(id);
        ResBoolSimpleInfo info = new ResBoolSimpleInfo(true,null,bc);
        return info;
    }

    @Override
    @Transactional(rollbackFor=Exception.class,timeout=60)
    public int findChapterCount(Pagination<DtoBaseChapter> queryPgn) {
        return mapper.findChapterCount(queryPgn);
    }

    @Override
    @Transactional(rollbackFor=Exception.class,timeout=60)
    public List<DtoBaseChapter> findChapterPageList(Pagination<DtoBaseChapter> queryPgn) {
        return mapper.findChapterPageList(queryPgn);
    }

    @Override
    public BaseChapter selectByPKandOrgan(Long id, Long authOrganizationId) {
        return mapper.selectByPKandOrgan(id, authOrganizationId);
    }

	@Override
	public Integer findByResourceId(String resourceId) {
		return mapper.findByResourceId(resourceId);
	}

	@Override
	public BaseChapter selectByLectureUrl(String lectureUrl) {
		return mapper.selectByLectureUrl(lectureUrl);
	}

	@Override
	public BaseChapter selectByCourseUrl(String courseUrl) {
		return mapper.selectByCourseUrl(courseUrl);
	}

	@Override
	public BaseChapter selectByCla7LectureUrl(Long lessonClassId,
			String lectureUrl) {
		return mapper.selectByCla7LectureUrl(lessonClassId, lectureUrl);
	}

	@Override
	public BaseChapter selectByCla7CourseUrl(Long lessonClassId, String courseUrl) {
		return mapper.selectByCla7CourseUrl(lessonClassId, courseUrl);
	}


}